package com.example.demo.jdbc;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

/**
 * @author Rocket
 * @version 10.0.1
 * @date 2021-08-22 10:18 AM
 */
@WebServlet(name="Batch Test", urlPatterns = {"/batch"})
public class BatchTest extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Connection conn = null;
        try {
            Class.forName("org.h2.Driver");
            conn = DriverManager.getConnection("jdbc:h2:C:/study/db/h2/bin/test;AUTO_SERVER=TRUE;AUTO_RECONNECT=TRUE", "sa", "123");
            resp.getWriter().println(conn);
           //conn.setAutoCommit(true);
            Statement stmt = conn.createStatement();

//            PreparedStatement stmt = conn.prepareStatement("insert into test (id, name, birthday) values( ?, ?, ?);");
//
//            for(int i = 0; i < 100; i++) {
//                stmt.setInt(1, 107 + i);
//                stmt.setString(2, "name" + (107 + i));
//                stmt.setDate(3, new Date(System.currentTimeMillis()));
//                stmt.addBatch();
//                if(i == 50) {
//                    throw new RuntimeException("DB Connection error");
//                }
//            }

            for(int x = 0; x < 100; x++){
                stmt.execute(String.format("insert into test (id, name) values( %d, '%s');", 107 + x, "name" + (107 + x)));
                if(x == 50) {
                    throw new RuntimeException("DB Connection error");
                }
            }
//            int count[] = stmt.executeBatch();
//            if(count.length > 0 && count.length <=100) {
//                resp.getWriter().println("Batch insert successfully");
//            } else {
//                resp.getWriter().println("failed to insert in batch");
//            }
           // conn.commit();

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            if(conn != null) {
               // try {
                   // conn.rollback();
                //} catch (SQLException ee) {
                //}
            }

            return;
        } finally {
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                }
            }
        }


    }
}
